package com.banciyuan.bcywebview.biz.post.cos;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.text.Editable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.CoserApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.factory.TimelineFactory;
import com.banciyuan.bcywebview.base.helper.ActionbarHelper;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.helper.timelinedatacenter.DetailDataHelper;
import com.banciyuan.bcywebview.base.view.dialog.ConfirmDialog;
import com.banciyuan.bcywebview.base.view.dialog.MyProgressDialog;
import com.banciyuan.bcywebview.base.view.listview.NoScrollListView;
import com.banciyuan.bcywebview.base.view.recycleview.NoScrollGridLayoutManager;
import com.banciyuan.bcywebview.base.view.recycleview.OnRecyclerItemClickListener;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.biz.circles.decoration.ItemOffsetDecoration;
import com.banciyuan.bcywebview.biz.post.Listener.OnTextChangeListener;
import com.banciyuan.bcywebview.biz.post.auto.AutoComplateHelper;
import com.banciyuan.bcywebview.biz.post.auto.AutoComplateNoLimteAdapter;
import com.banciyuan.bcywebview.biz.post.auto.IGetAutoComplate;
import com.banciyuan.bcywebview.biz.post.pic.PostImgAdapter;
import com.banciyuan.bcywebview.biz.post.succ.PostSuccActivity;
import com.banciyuan.bcywebview.biz.post.uploadpic.UploadAsyncHelper;
import com.banciyuan.bcywebview.biz.post.uploadpic.receiver.UploaderLoaderInter;
import com.banciyuan.bcywebview.biz.post.uploadpic.receiver.UploaderReceiver;
import com.banciyuan.bcywebview.biz.write.photoselecotor.model.PhotoModel;
import com.banciyuan.bcywebview.biz.write.photoselecotor.pselector.PhotoActivity;
import com.banciyuan.bcywebview.biz.write.write.WriteHelper;
import com.banciyuan.bcywebview.utils.common.UIUtils;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.sp.SPConstant;
import com.banciyuan.bcywebview.utils.sp.SPHelper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.Character;
import de.greenrobot.daoexample.model.DetailType;
import de.greenrobot.daoexample.model.Multi;
import de.greenrobot.daoexample.model.PostItem;

/**
 * Created by squall on 2015/12/30.
 */
public class CosPostActivity extends BaseActivity implements View.OnClickListener {

    protected ProgressbarHelper mProgressbarHelper;
    protected View mProgressbarView;
    protected ActionbarHelper mActionbarHelper;
    private View mActionBarView;
    private TextView tv_send;
    protected RecyclerView noScrollRecycler;
    private NoScrollListView noScrollListView;
    private RadioGroup rg_tongjin;
    private AutoCompleteTextView et_work;
    private LinearLayout rl_add_character;
    private RelativeLayout ll_set_info;
    private RelativeLayout ll_set_rights;
    private RadioButton rb_one;
    private RadioButton rb_two;
    protected MyProgressDialog mDialog;
    private TextView info_write;
    private TextView rights_write;
    private ImageView info_label;
    private ImageView rights_label;
    protected View edit_warn;

    private PostImgAdapter postImgAdapter;
    private CosCharacterAdapter cosCharacterAdapter;
    private UploadAsyncHelper uploadPicHelper;
    private AutoComplateNoLimteAdapter autoComplateAdapter;

    private ShowAdd showAdd;

    private List<de.greenrobot.daoexample.model.Character> clist = new ArrayList<Character>();
    private List<PhotoModel> plist = new ArrayList<>();
    private List<String> slist = new ArrayList<>();
    private Map<String, Multi> pathList = new HashMap<>();

    protected PostItem postItem;

    protected RequestQueue mQueue;

    private static final String work = "works";
    private static final String preview = "preview";
    public static final int GO_SETRIGHTS = 1000;
    public static final int GO_SETINFO = 1001;

    private int enter_nums = 1;

    protected boolean from_memory = false;
    private boolean send_flag = false;
    protected boolean edit = false;

    private ItemTouchHelper itemTouchHelper;
    private UploaderReceiver uploaderReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.post_coser_head);
        registerBroadCast();
        getItem(savedInstanceState);
        initArgs();
        initActionbar();
        initProgressbar();
        initUi();
        if (!edit) setItem();
        initAction();
        if (!edit) {
            initData();
            startImagePic();
            initDrag();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(uploaderReceiver);
    }

    private void initDrag() {
        itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
            @Override
            public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                int dragFlags = 0;
                int swipeFlags = 0;
                if (recyclerView.getLayoutManager() instanceof GridLayoutManager) {
                    dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
                } else {
                    dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
                }
                return makeMovementFlags(dragFlags, swipeFlags);
            }

            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                int fromPosition = viewHolder.getAdapterPosition();
                int toPosition = target.getAdapterPosition();
                if (fromPosition >= plist.size() || toPosition >= plist.size())
                    return false;
                if (fromPosition < toPosition) {
                    for (int i = fromPosition; i < toPosition; i++) {
                        Collections.swap(plist, i, i + 1);
                    }
                } else {
                    for (int i = fromPosition; i > toPosition; i--) {
                        Collections.swap(plist, i, i - 1);
                    }
                }
                postImgAdapter.notifyItemMoved(fromPosition, toPosition);
                return true;
            }

            @Override
            public boolean isLongPressDragEnabled() {
                return false;
            }

            @Override
            public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
                if (actionState != ItemTouchHelper.ACTION_STATE_IDLE && viewHolder != null) {
                    viewHolder.itemView.setAlpha(0.8f);
                }
                super.onSelectedChanged(viewHolder, actionState);
            }

            @Override
            public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                super.clearView(recyclerView, viewHolder);
                if (viewHolder != null) viewHolder.itemView.setAlpha(1f);
                postImgAdapter.notifyDataSetChanged();
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {

            }

        });
        itemTouchHelper.attachToRecyclerView(noScrollRecycler);
        noScrollRecycler.addOnItemTouchListener(new OnRecyclerItemClickListener(noScrollRecycler, new OnRecyclerItemClickListener.ItemTouchHelperGestureListener() {
            @Override
            public void onItemLongClick(RecyclerView.ViewHolder vh) {
                int fromPosition = vh.getAdapterPosition();
                if (fromPosition < plist.size()) {
                    itemTouchHelper.startDrag(vh);
                }
            }
        }));
    }

    private void startImagePic() {
        Intent intent = new Intent(CosPostActivity.this, PhotoActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("photos", (Serializable) plist);
        intent.putExtras(bundle);
        startActivityForResult(intent, WriteHelper.PICK_IMAGE);
    }

    private void getItem(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            from_memory = true;
            if (savedInstanceState.getSerializable("postitem") != null) {
                postItem = (PostItem) savedInstanceState.getSerializable("postitem");
            } else {
                postItem = new PostItem();
            }
            if (savedInstanceState.getSerializable("plist") != null) {
                plist = (List<PhotoModel>) savedInstanceState.getSerializable("plist");
            }

        } else {
            postItem = new PostItem();
        }
    }

    public void setItem() {
        if (!TextUtils.isEmpty(postItem.getWork())) {
            et_work.setText(postItem.getWork());
        }
        if (postItem.getCharacter() != null) {
            if (!postItem.getCharacter().isEmpty()) {
                clist.addAll(postItem.getCharacter());
            } else {
                Character character = new Character();
                character.setCoser(UserDataHelper.getInstance().getUname());
                clist.add(character);
            }
        } else {
            Character character = new Character();
            character.setCoser(UserDataHelper.getInstance().getUname());
            clist.add(character);
        }
        cosCharacterAdapter = new CosCharacterAdapter(clist, CosPostActivity.this, showAdd);
        noScrollListView.setAdapter(cosCharacterAdapter);

        if (!TextUtils.isEmpty(postItem.getType())) {
            if (postItem.getType().equals(work)) {
                rb_one.setChecked(true);
            } else {
                rb_two.setChecked(true);
            }
        }
    }

    protected void saveItem() {
        Character character;
        postItem.getCharacter().clear();
        for (int i = 0; i < noScrollListView.getChildCount(); i++) {
            character = new Character();
            View view = noScrollListView.getChildAt(i);
            TextView mtv = (TextView) view.findViewById(R.id.character_mname);
            TextView rtv = (TextView) view.findViewById(R.id.character_rname);
            character.setCoser(rtv.getText().toString().trim());
            character.setCharacter(mtv.getText().toString().trim());
            postItem.getCharacter().add(character);
        }
        postItem.setWork(et_work.getText().toString().trim());
        if (rb_one.isChecked()) {
            postItem.setType(work);
        } else {
            postItem.setType(preview);
        }
    }

    @Override
    protected void initArgs() {
        String default_tag = getIntent().getStringExtra(gotoUtil.INTENT_VALUE_ONE);
        String default_work = getIntent().getStringExtra(gotoUtil.INTENT_VALUE_TWO);
        if (!TextUtils.isEmpty(default_tag)) {
            postItem.getOptional().getTags().add(default_tag);
        }
        if (!TextUtils.isEmpty(default_work)) {
            postItem.setWork(default_work);
        }
        mQueue = VolleyQueue.getRquest(CosPostActivity.this);
        showAdd = new ShowAdd() {
            @Override
            public void show() {
                rl_add_character.setVisibility(View.VISIBLE);
                saveCharacter();
            }
        };
        uploadPicHelper = new UploadAsyncHelper(this, false);
    }

    @Override
    protected void initProgressbar() {
        mProgressbarView = findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                initData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    private void saveTagInDiskMemory() {
        Gson gson = new Gson();
        String tagStrOriginal = SPHelper.getString(this, SPConstant.SPNAME_MEMORYTAG + UserDataHelper.getInstance(this).getUid(), SPConstant.COSTAG, "[]");
        LinkedList<String> memoryTagList = gson.fromJson(tagStrOriginal, new TypeToken<LinkedList<String>>() {
        }.getType());
        memoryTagList.addAll(0, postItem.getOptional().getTags());
        while (memoryTagList.size() > 10) {
            memoryTagList.removeLast();
        }
        String tagStr = gson.toJson(new LinkedHashSet<>(memoryTagList));
        SPHelper.putString(this, SPConstant.SPNAME_MEMORYTAG + UserDataHelper.getInstance(this).getUid(), SPConstant.COSTAG, tagStr);
    }

    @Override
    protected void initData() {
        String url = HttpUtils.BASE_URL + CoserApi.getUploadparam();
        List<BcyPair> pairList = new ArrayList<BcyPair>();
        pairList.add(new BcyPair(HttpUtils.USER_TOKEN, UserDataHelper.getInstance(CosPostActivity.this).getToken()));
        Map<String, String> map = HttpUtils.getData(pairList);

        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    JSONObject jsonObject = new JSONObject(s);
                    JSONObject result = jsonObject.getJSONObject(HttpUtils.UPLOAD_DATA);
                    if (result.has("cp_id")) {
                        postItem.setCp_id(result.getString("cp_id"));
                    }
                    if (result.has("post_token")) {
                        postItem.setPost_token(result.getString("post_token"));
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

                mProgressbarHelper.onSuccess();
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                mProgressbarHelper.onFailed();
            }
        };

        StringRequestParam stringRequestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, onError);
        mQueue.add(stringRequestParam);
    }

    @Override
    protected void initActionbar() {
        mActionBarView = findViewById(R.id.base_action_bar);
        mActionbarHelper = new ActionbarHelper(this, mActionBarView);
        mActionbarHelper.setTitle(getString(R.string.post_cos));
        mActionbarHelper.addItemOneText(getString(R.string.post));
        tv_send = (TextView) findViewById(R.id.base_action_bar_home_text_item);
        tv_send.setOnClickListener(this);
        mActionbarHelper.setActionCallbacks(new ActionbarHelper.OnActionCallbacks() {
            @Override
            public void onBackClick() {
                finishActivity();
            }

            @Override
            public void onActionClick(int id) {

            }
        });
    }

    @Override
    protected void initUi() {
        noScrollRecycler = (RecyclerView) findViewById(R.id.group_noscroll);
        rg_tongjin = (RadioGroup) findViewById(R.id.radio_tongjin);
        et_work = (AutoCompleteTextView) findViewById(R.id.cos_work);
        rl_add_character = (LinearLayout) findViewById(R.id.rl_add_character);
        ll_set_info = (RelativeLayout) findViewById(R.id.ll_info_set);
        ll_set_rights = (RelativeLayout) findViewById(R.id.ll_rights_set);
        noScrollListView = (NoScrollListView) findViewById(R.id.lv_character);
        rb_one = (RadioButton) findViewById(R.id.radio_tongren);
        rb_two = (RadioButton) findViewById(R.id.radio_untongren);
        info_write = (TextView) findViewById(R.id.info_has_write);
        rights_write = (TextView) findViewById(R.id.right_has_write);
        info_label = (ImageView) findViewById(R.id.info_label);
        rights_label = (ImageView) findViewById(R.id.rights_label);
        edit_warn = findViewById(R.id.edit_warn);
        RecyclerView.ItemAnimator animator = noScrollRecycler.getItemAnimator();
        if (animator instanceof SimpleItemAnimator) {
            ((SimpleItemAnimator) animator).setSupportsChangeAnimations(false);
        }
        noScrollRecycler.setLayoutManager(new NoScrollGridLayoutManager(this, 5));
        noScrollRecycler.addItemDecoration(new ItemOffsetDecoration(UIUtils.dip2px(4, this)));

        rb_one.setText(getString(R.string.offical_work));
        rb_two.setText(getString(R.string.prework));

        if (!edit) {
            postImgAdapter = new PostImgAdapter(plist, CosPostActivity.this, new PostImgAdapter.BeforeOpenAlbum() {
                @Override
                public void beforeOpen() {
                    saveItem();
                }
            });
            noScrollRecycler.setAdapter(postImgAdapter);
        }
        DialogInterface.OnClickListener cancelOnClick = null;
        DialogInterface.OnCancelListener onCancelClick = null;
        cancelOnClick = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mDialog.dismiss();
            }
        };
        MyProgressDialog.Builder mBuilder = new MyProgressDialog.Builder(this);
        mDialog = mBuilder.setCancelButton(cancelOnClick).setOnCancelButton(onCancelClick).create();
    }

    @Override
    protected void initAction() {
        rl_add_character.setOnClickListener(this);
        ll_set_info.setOnClickListener(this);
        ll_set_rights.setOnClickListener(this);

        final IGetAutoComplate iGetAutoComplate = new IGetAutoComplate() {
            @Override
            public void getComplateList(String s, boolean show) {
                dealAutoJson(s, show);
            }
        };

        et_work.addTextChangedListener(new OnTextChangeListener() {
            @Override
            public void afterTextChanged(Editable s) {
                if (!et_work.isPerformingCompletion()) {
                    if (!TextUtils.isEmpty(s.toString())) {
                        String url = HttpUtils.BASE_URL + CoserApi.getComplete();
                        AutoComplateHelper autoHelper = new AutoComplateHelper(CosPostActivity.this, iGetAutoComplate, "work");
                        autoHelper.findServerTitle(s, !from_memory, url);
                    }
                    if (TextUtils.isEmpty(s.toString())) {
                        if (!from_memory) {
                            et_work.dismissDropDown();
                        }
                        from_memory = false;
                    }
                }
            }
        });
    }

    private void dealAutoJson(String s, boolean show) {
        if (StatusCodeUtils.dealStatusCode(s, this)) {
            try {
                JSONObject jsonObject = new JSONObject(s);
                JSONArray jsonArray = jsonObject.getJSONArray("data");
                slist.clear();
                for (int i = 0; i < jsonArray.length(); i++) {
                    slist.add(jsonArray.getString(i));
                }
                autoComplateAdapter = new AutoComplateNoLimteAdapter(slist, this, et_work.getText().toString());
                et_work.setAdapter(autoComplateAdapter);

            } catch (Exception e) {
            }
        }
        if (show) {
            if (!this.isFinishing()) {
                et_work.showDropDown();
            }
        }
    }

    private void changeSelectImg(List<PhotoModel> templist) {
        plist.clear();
        plist.addAll(templist);

        if (null == postImgAdapter) {
            postImgAdapter = new PostImgAdapter(plist, CosPostActivity.this, new PostImgAdapter.BeforeOpenAlbum() {
                @Override
                public void beforeOpen() {
                    saveItem();
                }
            });
            noScrollRecycler.setAdapter(postImgAdapter);
        } else {
            postImgAdapter.notifyDataSetChanged();
        }
        noScrollRecycler.post(new Runnable() {
            @Override
            public void run() {
                beginUpload();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == WriteHelper.PICK_IMAGE) {
            if (data != null && data.getExtras() != null && data.getExtras().getSerializable("photos") != null) {
                List<PhotoModel> temp = (ArrayList<PhotoModel>) data.getExtras().getSerializable("photos");
                if (temp != null) {
                    changeSelectImg(temp);
                }
            }
            if (enter_nums == 1) {
                enter_nums++;
                showSoftKeyBoard();
            }
        } else if (requestCode == GO_SETRIGHTS) {
            PostItem tempItem = (PostItem) data.getSerializableExtra("postitem");
            postItem.setAuthority(tempItem.getAuthority());
        } else if (requestCode == GO_SETINFO) {
            if (data != null) {
                PostItem tempItem = (PostItem) data.getSerializableExtra("postitem");
                boolean flag = data.getBooleanExtra("change", false);
                if (flag) {
                    info_label.setImageDrawable(getResources().getDrawable(R.drawable.more_info_pink));
                    info_write.setVisibility(View.VISIBLE);
                } else {
                    info_label.setImageDrawable(getResources().getDrawable(R.drawable.more_info_gray));
                    info_write.setVisibility(View.GONE);
                }
                postItem.setOptional(tempItem.getOptional());
            }
        }
    }

    private void showSoftKeyBoard() {
        InputMethodManager inputManager = (InputMethodManager)
                et_work.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (null != inputManager && inputManager.isActive()) {
            inputManager.showSoftInputFromInputMethod(et_work.getWindowToken(), 0);
            inputManager.toggleSoftInput(0, 0);
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.rl_add_character:
                addCharater();
                break;
            case R.id.ll_rights_set:
                saveItem();
                intent.setClass(CosPostActivity.this, CosRightsActivity.class);
                intent.putExtra(gotoUtil.INTENT_VALUE_ONE, postItem);
                startActivityForResult(intent, GO_SETRIGHTS);
                break;
            case R.id.ll_info_set:
                saveItem();
                intent.setClass(CosPostActivity.this, CosInfoActivity.class);
                intent.putExtra(gotoUtil.INTENT_VALUE_ONE, postItem);
                startActivityForResult(intent, GO_SETINFO);
                break;
            case R.id.base_action_bar_home_text_item:
                beginPost();
                break;
        }
    }

    protected void addCharater() {
        saveCharacter();
        if (clist.size() < 10) {
            Character character = new Character();
            clist.add(character);
            cosCharacterAdapter.changeFocusFlag();
            cosCharacterAdapter.notifyDataSetChanged();
            if (clist.size() >= 10) {
                rl_add_character.setVisibility(View.GONE);
            }
        } else {
            MyToast.show(CosPostActivity.this, getString(R.string.over_ten));
        }
    }

    public interface ShowAdd {
        void show();
    }

    protected void beginPost() {
        if (vaild()) {
            List<Multi> upload = new ArrayList<>();
            for (PhotoModel p : plist) {
                Multi m = pathList.get(p.getOriginalPath());
                if (m != null) {
                    upload.add(m);
                }
            }
            if (upload.size() == plist.size()) {
                if (!isFinishing()) {
                    mDialog.show();
                    postCos(upload);
                }
            } else {
                MyToast.show(this, getString(R.string.img_still_upload));
            }
        }
    }

    private void registerBroadCast() {
        uploaderReceiver = new UploaderReceiver(new UploaderLoaderInter() {
            @Override
            public void onProgress(double progress, String key) {
                for (PhotoModel p : plist) {
                    if (p.getOriginalPath().equals(key)) {
                        p.setProgress(progress);
                        postImgAdapter.notifyItemChanged(plist.indexOf(p));
                    }
                }
            }

            @Override
            public void onFinish(Multi m) {
                if (m.isUpdate_status()) {
                    pathList.put(m.getLocal_path(), m);
                    for (PhotoModel p : plist) {
                        if (p.getOriginalPath().equals(m.getLocal_path())) {
                            p.setIsUpload(true);
                            postImgAdapter.notifyItemChanged(plist.indexOf(p));
                        }
                    }
                } else {
                    for (PhotoModel p : plist) {
                        if (p.getOriginalPath().equals(m.getLocal_path())) {
                            p.setIsfail(true);
                            postImgAdapter.notifyItemChanged(plist.indexOf(p));
                        }
                    }
                }

            }

            @Override
            public void onFail() {

            }
        });
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(UploaderLoaderInter.PROGRESS_KEY);
        intentFilter.addAction(UploaderLoaderInter.UPLOAD_FINISH_KEY);
        registerReceiver(uploaderReceiver, intentFilter);
    }

    private void beginUpload() {
        List<PhotoModel> uploadList = new ArrayList<>();
        for (PhotoModel p : plist) {
            if (pathList.get(p.getOriginalPath()) == null) {
                uploadList.add(p);
            } else {
                p.setIsUpload(true);
                postImgAdapter.notifyItemChanged(plist.indexOf(p));
            }
        }
        uploadPicHelper.getToken(HttpUtils.CPID, postItem.getCp_id(), CoserApi.getUploadtoken(), uploadList);
    }

    protected boolean vaild() {
        if (TextUtils.isEmpty(et_work.getText().toString())) {
            MyToast.show(CosPostActivity.this, getString(R.string.work_cant_benull));
            return false;
        }
        for (int i = 0; i < noScrollListView.getChildCount(); i++) {
            View view = noScrollListView.getChildAt(i);
            TextView tv1 = (TextView) view.findViewById(R.id.character_mname);
            TextView tv2 = (TextView) view.findViewById(R.id.character_rname);
            if (TextUtils.isEmpty(tv1.getText().toString())) {
                MyToast.show(CosPostActivity.this, getString(R.string.character_cant_benull));
                return false;
            }
            if (TextUtils.isEmpty(tv2.getText().toString())) {
                MyToast.show(CosPostActivity.this, getString(R.string.character_cant_benull));
                return false;
            }
        }
        if (plist.isEmpty() && !edit) {
            MyToast.show(CosPostActivity.this, getString(R.string.pic_cant_benull));
            return false;
        }
        return true;
    }

    private void removeRepeatTag() {
        if (null == postItem.getOptional() || null == postItem.getOptional().getTags())
            return;
        List<String> repeatTag = new ArrayList<>();
        for (String tag : postItem.getOptional().getTags()) {
            if (tag.equals(postItem.getWork())) {
                repeatTag.add(tag);
                continue;
            }
            for (Character character : postItem.getCharacter()) {
                if (tag.equals(character.getCharacter()))
                    repeatTag.add(tag);
            }
        }
        postItem.getOptional().getTags().removeAll(repeatTag);
    }

    private void postCos(List<Multi> path) {
        if (send_flag) return;
        else send_flag = true;
        String url = HttpUtils.BASE_URL + CoserApi.getNewcos();
        List<BcyPair> pairs = new ArrayList<>();
        pairs.add(new BcyPair(HttpUtils.USER_TOKEN, UserDataHelper.getInstance(CosPostActivity.this).getToken()));
        String json = getPostJson(path);
        pairs.add(new BcyPair(HttpUtils.UPLOAD_DATA, json));
        Map<String, String> map = HttpUtils.getData(pairs);

        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                if (StatusCodeUtils.dealStatusCode(s, CosPostActivity.this)) {
                    try {
                        JSONObject jsonObject = new JSONObject(s);
                        JSONObject result = jsonObject.getJSONObject(HttpUtils.UPLOAD_DATA);
                        Intent detail = DetailDataHelper.creatCosDetail(CosPostActivity.this, result.getString(HttpUtils.RPID), result.getString(HttpUtils.CPID), false, false);
                        Intent succ = new Intent(CosPostActivity.this, PostSuccActivity.class);
                        succ.putExtra("detailtype", newDetailType(result.getString(HttpUtils.RPID), result.getString(HttpUtils.CPID)));
                        startActivities(new Intent[]{detail, succ});
                        finish();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                if (!CosPostActivity.this.isFinishing()) {
                    mDialog.dismiss();
                }
                saveTagInDiskMemory();
                send_flag = false;
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                mDialog.dismiss();
                MyToast.show(CosPostActivity.this, getString(R.string.cos_post_fail));
                send_flag = false;
            }
        };

        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, onError);
        requestParam.setRetryPolicy(new DefaultRetryPolicy(60000, 0,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        mQueue.add(requestParam);

    }

    protected String getPostJson(List<Multi> path) {
        Gson gson = new Gson();
        postItem.getCharacter().clear();
        if (rb_one.isChecked()) {
            postItem.setType(work);
        } else if (rb_two.isChecked()) {
            postItem.setType(preview);
        }
        for (int i = 0; i < noScrollListView.getChildCount(); i++) {
            View view = noScrollListView.getChildAt(i);
            TextView tv1 = (TextView) view.findViewById(R.id.character_mname);
            TextView tv2 = (TextView) view.findViewById(R.id.character_rname);
            Character character = new Character();
            character.setCoser(tv2.getText().toString());
            character.setCharacter(tv1.getText().toString());
            postItem.getCharacter().add(character);
        }
        postItem.setWork(et_work.getText().toString());
        for (Multi m : path) {
            m.setOrigin(null);
            m.setLocal_path(null);
            m.setType(null);
        }
        postItem.setMulti(path);
        removeRepeatTag();
        return gson.toJson(postItem);
    }

    private void saveCharacter() {
        for (int i = 0; i < noScrollListView.getChildCount(); i++) {
            View view = noScrollListView.getChildAt(i);
            TextView tv1 = (TextView) view.findViewById(R.id.character_mname);
            TextView tv2 = (TextView) view.findViewById(R.id.character_rname);
            Character character = clist.get(i);
            character.setCoser(tv2.getText().toString());
            character.setCharacter(tv1.getText().toString());
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (event.getKeyCode()) {
            case KeyEvent.KEYCODE_BACK:
                finishActivity();
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void finishActivity() {
        if (!mDialog.isShowing() && !isFinishing()) {
            ConfirmDialog.Builder builder = new ConfirmDialog.Builder(this);
            builder.setDescString(getString(R.string.not_save_warn))
                    .setActionString(getString(R.string.continue_post))
                    .setCancelString(getString(R.string.cancel_post))
                    .setCancelClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            finish();
                        }
                    }).create().show();
        } else {
            mDialog.dismiss();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable("postitem", postItem);
        outState.putSerializable("plist", (Serializable) plist);
    }

    private DetailType newDetailType(String rp_id, String cp_id) {
        DetailType detailType = new DetailType();
        detailType.setRp_id(rp_id);
        detailType.setCp_id(cp_id);
        detailType.setTimelineType(TimelineFactory.TIMELINE_TYPE_COSER);
        return detailType;
    }


}
